<template>
  <form class="dh-form">
    <slot></slot>
  </form>

</template>

<script setup lang="ts">
import { provide } from "vue";
import type {
  FormContext,
  FormItemContext,
  FormProps,
  FormInstance,
} from "./type";
import { FormContextKey } from "./type";
defineOptions({
  name: "DhForm",
});
let fileds: FormItemContext[] = [];
const addField = (filed: any) => {
  fileds.push(filed);
};
const removeField = (filed: any) => {
  if (filed.prop) {
    fileds.splice(fileds.indexOf(filed), 1);
  }
};
const validate = async () => {
  let validateError = {};
  for (let filed of fileds) {
    try {
      await filed.validate("");
    } catch (error: any) {
      validateError = {
        ...validateError,
        ...error,
      };
    }
  }

  if (Object.keys(validateError).length == 0) return true;
  return Promise.reject(validateError);
};
const resetFields = (keys: string[] = []) => {
  let filterFields =
    keys.length > 0
      ? fileds.filter((fileds) => keys.includes(fileds.prop!))
      : fileds;
  filterFields.forEach((filed) => filed.resetField!());
};
const clearValidate = (keys: string[] = []) => {
  let filterFields =
    keys.length > 0
      ? fileds.filter((fileds) => keys.includes(fileds.prop!))
      : fileds;
  filterFields.forEach((filed) => filed.clearValidate!());
};
const props = defineProps<FormProps>();
//向子组件传入数据
provide(FormContextKey, {
  ...props,
  addField,
  removeField,
});

defineExpose<FormInstance>({
  validate,
  resetFields,
  clearValidate,
});
</script>

<style scoped></style>
